# -*- coding: utf-8 -*-

from exceptions import Exception
from datetime import datetime

import feedparser
import feedfinder

from stream.mockable import mockable

@mockable
def find_feed(url, **kwargs):
    return feedfinder.feed(url, **kwargs)

@mockable
def retrieve_feed(url, **kwargs):
    return feedparser.parse(url, **kwargs)

class FeedParsingError(Exception):
    def __init__(self, feed_url, description):
        self.feed_url = feed_url
        self.description = description

    def __unicode__(self):
        return 'Error parsing feed %s, description: %s' % (self.feed_url, self.description)

    def __str__(self):
        return unicode(self)

def parseDateRfc822(date_string):
    return convertDate(feedparser._parse_date_rfc822(date_string))

def parseDateIso8601(date_string):
    return convertDate(feedparser._parse_date_iso8601(date_string))

def convertDate(date):
    """
    Converts a 9-tuple date representation returned by 'feedparser' into a normal Python datetime
    """
    return datetime(*date[0:6])
